package com.neteast.androidclient.newscenter.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.neteast.androidclient.newscenter.service.DownLoadService;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;

public class ApkManager extends AsyncTask<Object, Integer, File>{
	
	
	private Context mContext;
	private NotificationHelper notificationHelper;
	private long UNIT=1;
	
	
	public ApkManager(Context context){
		this.mContext=context;
		notificationHelper = new NotificationHelper(mContext);
	}
	
	
	private void stopManager() {
		if (notificationHelper!=null) {
			notificationHelper.completed();	
			mContext.stopService(new Intent(mContext, DownLoadService.class));
		}
	}
	
	private void installApk(File file) {
		Intent intent = new Intent();    
		intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		mContext.startActivity(intent);
	}

	@Override
	protected File doInBackground(Object... params) {
		try {
			String path=(String) params[0];
			long length=(Long) params[1];
			URL url=new URL(path);
			HttpURLConnection conn=(HttpURLConnection) url.openConnection();
			InputStream in = conn.getInputStream();
			UNIT=length/100;
			File file=new File(Environment.getExternalStorageDirectory(), url.getFile().substring(url.getFile().lastIndexOf("/")));
			FileOutputStream fos=new FileOutputStream(file);
			byte[] buffer=new byte[1024];
			int len=0;
			long completed=0;
			while((len=in.read(buffer))>0){
				completed+=len;
				fos.write(buffer,0,len);
				onProgressUpdate((int) (completed/UNIT));
			}
			in.close();
			fos.close();
			return file;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		notificationHelper.createNotification("正在更新消息盒子");
	}

	@Override
	protected void onPostExecute(File result) {
		super.onPostExecute(result);
		if (result!=null) {
			Toast.makeText(mContext, "消息盒子下载成功，安装成功后请重启机器", Toast.LENGTH_SHORT).show();
			installApk(result);	
		}else {
			Toast.makeText(mContext, "消息盒子下载失败，请重启机器", Toast.LENGTH_SHORT).show();
		}
		stopManager();
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		notificationHelper.progressUpdate(values[0]);
	}

	@Override
	protected void onCancelled() {
		super.onCancelled();
		stopManager();
	}
}
